/**
 * Created by hjqi on 2016/5/19.
 */
module.controller('ServiceDetailController', ["$scope", "$cookies", "$stateParams", "k8sService","$timeout","$document",
    function ($scope, $cookies, $stateParams, k8sService,$timeout,$document){
        var loadData = function() {
            var controller = $scope.svc.dbJson.rc;
            if ($scope.svc.dbJson.petset)
                controller = $scope.svc.dbJson.petset;
            var env = controller.spec.template.spec.containers[0].env;
            if (env)
                $scope.env = env;
            var ports = $scope.svc.dbJson.node.ports;
            if (ports) {
                // 仅仅是为了兼容旧的协议访问方式，建议尽快删除
                ports.forEach(function(portInfo) {
                    if(!portInfo.address){

                    }
                    if (portInfo.accessProtocol === undefined) {
                        portInfo.accessProtocol = "HTTP";
                        portInfo.address = 'http://'+$scope.svc.app+'.'+ $scope.ns+ '.naturecloud.io';
                    }
                });
                $scope.ports = ports;
            }

            //$scope.volumes = $scope.svc.dbJson.node.volumes;
            $scope.volumes = [];
            var _vol_map = {};
            //$scope.volumes.forEach(function(volume){
            $scope.svc.dbJson.node.volumes.forEach(function(volume){
                /**
                 *  IsDefault means not create by scale
                 */
                if(volume.IsDefault !== undefined){
                    var _vol = {};
                    if(volume.mountObj){
                        _vol = {
                            "volumeIds":volume.mountObj.name,
                            "mountTargetPath":volume.mountTargetPath
                        };
                    }else{
                        _vol = {
                            "volumeIds":volume.name,
                            "mountTargetPath":volume.mountTargetPath
                        };
                    }

                    _vol_map[volume.mountName] = _vol;
                    $scope.volumes.push(_vol);
                }else{
                    if(_vol_map[volume.mountName]){
                        _vol_map[volume.mountName].volumeIds += ","+volume.name;
                    }else{
                        console.log("should not run here");
                    }
                }

            });
            //volume.volumeIds = _vol_array.toString();
        }

        $scope.tabs = {};
        $scope.ns = $cookies.get("username");
        $scope.pods = [];
        $scope.appStatus = undefined;
        $scope.curPod = undefined;
        $scope.activeIdx = 0;

        var Idx2EvtMap = {
            "1":"getLogEvt",
            "2":"getShellEvt",
            "3":"getMonitorEvt"
        }

        $scope._name = $stateParams.serviceName;
        if ($stateParams.service) {
            $scope._name = $stateParams.service.app;
        }
        //split get pods logic from get service function
        //loadPodData();

        var serviceName = $stateParams.serviceName;
        var clusterId = $stateParams.clusterId;
        if ($stateParams.service) {
            $scope.svc = $stateParams.service;
            loadPodData();
            loadData();
        } else {
            k8sService.getServices(serviceName,clusterId).then(function(result){
                $scope.svc = result.data[0];
                loadPodData();
                loadData();
            }, function(err){
                alertify.alert('query applications err', ret.data);
            });
        }

        $scope.$watch('svc',function(newvalue,oldvalue){
            if($scope.svc !== undefined){
                $scope.appStatus = $scope.svc.totalStatue;
                //loadPodData();
            }
        });

        $scope.$watch('appStatus',function(newvalue,oldvalue){
            if($scope.appStatus !== undefined){
                if($scope.appStatus === 'stop'){
                    var test = angular.element(document.getElementById('test1'));
                    test.disabled = true;
                    $scope.noPod = true;
                }

            }
        });

        /**
         *  emit ative tab event
         */
        $scope.$watch('curPod',function(newvalue,oldvalue){
            if($scope.curPod !== undefined && $scope.activeIdx !== 0)
                $scope.TabEmit(Idx2EvtMap[$scope.activeIdx]);
        });

        $scope.addClick = function(idx){
            $scope.activeIdx = idx;
            // TODO add more case
            // temporary only set 2
            if(idx === 1 || idx === 2 || idx === 3){
                $scope.TabEmit(Idx2EvtMap[idx]);
            }

        };

        $scope.TabEmit = function(evt){
            $scope.$broadcast(evt,$scope.curPod);
        };

        $scope.projects = [];

        function loadPodData(){
            //k8sService.getpodStatus({app:$scope._name}).then(function (ret) {
            k8sService.getpodStatus($scope.svc.dbJson).then(function (ret) {

                    ret.data.items.forEach(function(item,index){
                        var _pod = {"replicasname": "", "phase": ""};
                        _pod.replicasname = item.metadata.name;
                        /*var name = {
                          name : item.metadata.name
                        };*/
                        $scope.projects.push(item);
                        if(index === 0)
                            $scope.curPod = item;

                        // use containerStatuses state
                        // 如果status.containerStatuses为空，则用status.phase
                        if (item.status.containerStatuses) {
                            _pod.phase = getState(item.status.containerStatuses[0].state);
                            if (_pod.phase === 'waiting') {
                                if (item.status.containerStatuses[0].state['waiting'].reason !== undefined &&
                                    item.status.containerStatuses[0].state['waiting'].reason === 'CrashLoopBackOff'){
                                    _pod.phase = 'Error';
                                }else{
                                    svcStatus = $scope.svc.totalStatue ;
                                    if( "stop" ===svcStatus ){
                                        svcStatus="stoping" ;
                                    }else if( "start" ===svcStatus){
                                        svcStatus = "starting" ;
                                    }else{
                                        svcStatus = "" ;
                                    }
                                    _pod.phase = svcStatus  ||_pod.phase;
                                }
                                if( item.status.containerStatuses[0].state['waiting'].reason !== undefined){
                                    _pod.reason = item.status.containerStatuses[0].state['waiting'].reason ;
                                }
                            }

                            _pod.lastState = item.status.containerStatuses[0].lastState;
                        }else
                            _pod.phase = item.status.phase;
                        _pod.hostIP = item.status.hostIP;
                        if( _pod.phase !== 'Failed' && _pod.phase !== 'termination'){
                            _pod.reason = _pod.reason||"" ;
                            $scope.pods.push(_pod);
                        }else{
                            console.log("[Error]"+_pod.replicasname+".status=:"+ _pod.phase) ;
                        }

                    });

                },
                function(){
                    alertify.error('get pod error');
                });
        }

        function getState(obj){
            for (var st in obj) {
                return st;
            }
        }
      /**
       * by jfgao on 2017/04/17
       * 明细页面动效
       * */
      setTimeout(function () {
        var height = jQuery('.tab-content').css('height');
        jQuery('.nav_side').css('height', height);
        jQuery('.nav_side>ul').css('width', jQuery('.nav_side').css('width'));
        /*var nav_Left = jQuery('.nav.nav-tabs>li:eq(0)').position().left;
        var nav_width = jQuery('.nav.nav-tabs>li:eq(0)').css("width");
     */

      }, 100);

      $scope.addActive=function (val) {

        jQuery(".nav_side li a").removeClass("active");
        jQuery(".nav_side li").eq(val).children('a').addClass("active");

        side_height = jQuery('.nav_side>ul>li').eq(val).css("height");
        var margin_Top=val*parseInt(side_height);
        jQuery('.side_line').css({'margin-top': margin_Top})
      };


    }
]);